import express from "express";
import url from "url";

import { GithubApiService } from "../GithubApiService";
import { Repo } from "../model/Repo";
import { User } from "../model/User";
import * as Lodash from "lodash";
import { Request, Response } from "express-serve-static-core";

let routers = express.Router();

routers.get("/github", (req: Request, res: Response) => {
  let username: any = url.parse(req.url, true).query.username;
  let api: GithubApiService = new GithubApiService();

  api.getUserInfo(username, (user: User) => {
    api.getRepo(user.login, (repos: Repo[]) => {
      let sortRepos = Lodash.sortBy(repos, [(repo: Repo) => repo.size * -1]);
      user.repos = sortRepos;
      // res
      res.send(user);
    });
  });
});

routers.post("/postgithub", (req: Request, res: Response) => {
  let username = req.body.username;
  let api: GithubApiService = new GithubApiService();

  api.getUserInfo(username, (user: User) => {
    api.getRepo(user.login, (repos: Repo[]) => {
      let sortRepos = Lodash.sortBy(repos, [(repo: Repo) => repo.size * -1]);
      user.repos = sortRepos;
      // res
      res.send(user);
    });
  });
});

export default routers;
